#region Copyright (c) 2006-2012 nHydrate.org, All Rights Reserved
// --------------------------------------------------------------------- *
//                           NHYDRATE.ORG                                *
//              Copyright (c) 2006-2012 All Rights reserved              *
//                                                                       *
//                                                                       *
// This file and its contents are protected by United States and         *
// International copyright laws.  Unauthorized reproduction and/or       *
// distribution of all or any portion of the code contained herein       *
// is strictly prohibited and will result in severe civil and criminal   *
// penalties.  Any violations of this copyright will be prosecuted       *
// to the fullest extent possible under law.                             *
//                                                                       *
// THE SOURCE CODE CONTAINED HEREIN AND IN RELATED FILES IS PROVIDED     *
// TO THE REGISTERED DEVELOPER FOR THE PURPOSES OF EDUCATION AND         *
// TROUBLESHOOTING. UNDER NO CIRCUMSTANCES MAY ANY PORTION OF THE SOURCE *
// CODE BE DISTRIBUTED, DISCLOSED OR OTHERWISE MADE AVAILABLE TO ANY     *
// THIRD PARTY WITHOUT THE EXPRESS WRITTEN CONSENT OF THE NHYDRATE GROUP *
//                                                                       *
// UNDER NO CIRCUMSTANCES MAY THE SOURCE CODE BE USED IN WHOLE OR IN     *
// PART, AS THE BASIS FOR CREATING A PRODUCT THAT PROVIDES THE SAME, OR  *
// SUBSTANTIALLY THE SAME, FUNCTIONALITY AS THIS PRODUCT                 *
//                                                                       *
// THE REGISTERED DEVELOPER ACKNOWLEDGES THAT THIS SOURCE CODE           *
// CONTAINS VALUABLE AND PROPRIETARY TRADE SECRETS OF NHYDRATE,          *
// THE REGISTERED DEVELOPER AGREES TO EXPEND EVERY EFFORT TO             *
// INSURE ITS CONFIDENTIALITY.                                           *
//                                                                       *
// THE END USER LICENSE AGREEMENT (EULA) ACCOMPANYING THE PRODUCT        *
// PERMITS THE REGISTERED DEVELOPER TO REDISTRIBUTE THE PRODUCT IN       *
// EXECUTABLE FORM ONLY IN SUPPORT OF APPLICATIONS WRITTEN USING         *
// THE PRODUCT.  IT DOES NOT PROVIDE ANY RIGHTS REGARDING THE            *
// SOURCE CODE CONTAINED HEREIN.                                         *
//                                                                       *
// THIS COPYRIGHT NOTICE MAY NOT BE REMOVED FROM THIS FILE.              *
// --------------------------------------------------------------------- *
#endregion
using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using nHydrate.Generator.Common.Util;
using nHydrate.Generator.Models;

namespace nHydrate.Generator.MySQLInstaller.ProjectItemGenerators.SQLStoredProcedureAll
{
	internal class SQLDeleteBusinessObjectTemplate : ISQLGenerate
	{
		private ModelRoot _model;
		private Table _currentTable;

		#region Constructors

		public SQLDeleteBusinessObjectTemplate(ModelRoot model, Table currentTable)
		{
			_model = model;
			_currentTable = currentTable;
		}

		#endregion

		#region GenerateContent

		public void GenerateContent(StringBuilder sb)
		{
			try
			{
				this.AppendFullTemplate(sb);
			}
			catch (Exception ex)
			{
				throw;
			}
		}

		#endregion

		private void AppendFullTemplate(StringBuilder sb)
		{
			try
			{
				var moduleSuffix = string.Empty;
				if (!string.IsNullOrEmpty(_model.ModuleName))
					moduleSuffix = _model.ModuleName + "_";

				var storedProcedureName = _model.GetStoredProcedurePrefix() + "_" + _currentTable.PascalName + "_" + moduleSuffix + "Delete";

				sb.AppendLine("if exists (select * from dbo.sysobjects where id = object_id(N'[" + _currentTable.GetSQLSchema() + "].[" + storedProcedureName + "]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)");
				sb.AppendLine("	drop procedure [" + _currentTable.GetSQLSchema() + "].[" + storedProcedureName + "]");
				sb.AppendLine("GO");
				sb.AppendLine();

				//Just drop the procedure if no CRUD SP
				if (!_model.Database.UseGeneratedCRUD)
					return;

				sb.AppendLine("CREATE PROCEDURE [" + _currentTable.GetSQLSchema() + "].[" + storedProcedureName + "]");
				sb.AppendLine("(");
				sb.Append(BuildParameterList());
				sb.AppendLine(")");
				sb.AppendLine("AS");
				sb.AppendLine("SET NOCOUNT OFF;");
				sb.AppendLine();
				sb.Append(SQLGeneratedBodyHelper.SQLDeleteBusinessObjectBody(_currentTable, _model));
				sb.AppendLine("GO");
				sb.AppendLine();
				if (_model.Database.GrantExecUser != string.Empty)
				{
					sb.AppendFormat("GRANT EXECUTE ON [" + _currentTable.GetSQLSchema() + "].[{0}] TO [{1}]", storedProcedureName, _model.Database.GrantExecUser).AppendLine();
					sb.AppendLine("GO");
					sb.AppendLine();
				}

			}
			catch (Exception ex)
			{
				throw;
			}

		}
		#region string methods
		protected string BuildParameterList()
		{
			var items = new List<Column>(_currentTable.PrimaryKeyColumns.OrderBy(x => x.Name));
			var index = 0;
			var output = new StringBuilder();

			var tableList = _currentTable.GetTableHierarchy();
			foreach (var table in tableList)
			{
				foreach (var relation in table.ChildRoleRelations)
				{
					foreach (ColumnRelationship columnRelationship in relation.ColumnRelationships)
					{
						var parentColumn = columnRelationship.ParentColumn;
						var parentTable = parentColumn.ParentTable;
						if (parentTable.Generated)
						{
							output.Append("\t@" + relation.RoleName + parentTable.DatabaseName + "_" + parentColumn.ToDatabaseCodeIdentifier() + " ");
							output.Append(parentColumn.GetSQLDefaultType() + " = null,");
							output.AppendLine("#Entity Framework Required Parent Keys be passed in: Table '" + parentTable.DatabaseName + "'");
						}
					}
				}
			}

			foreach (var column in items.OrderBy(x => x.Name))
			{
				output.Append("\t@Original_");
				output.Append(column.ToDatabaseCodeIdentifier());
				output.Append(" ");
				output.Append(column.GetSQLDefaultType());
				if (index < items.Count - 1) output.Append(",");
				output.AppendLine();
				index++;
			}
			return output.ToString();
		}

		#endregion


	}
}